package javaseof10day.day9.am.demo1;

/*

 * 描述：mvc中的c，用来管理模型层的数据
 * function ：增、删、改、查、保存、更新
 * */
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;

/*
 * Cotroller类集中对ArrayList<Student>进行操作
 * @Author nazi
 * @version 1.0
 * */
public class Cotroller {

	// student数据集合
	private ArrayList<Student> list;

	public Cotroller(ArrayList<Student> l) {
		this.list = l;
	}

	/*
	 * rturn a ArrayList<Student>
	 */
	public ArrayList<Student> getList() {
		return list;
	}

	/*
	 * 初始化Student数组
	 */
	public void setList(ArrayList<Student> list) {
		this.list = list;
	}

	/*
	 * add a student to the List
	 */
	public void add(Student s) {
		list.add(s);
	}

	/*
	 * remove the student from list
	 */
	public void remove(int id) {
		for (Iterator<Student> iter = list.iterator(); iter.hasNext();) {
			Student s = iter.next();

			if (s.getNum() == id) {
				list.remove(s);
			}
		}
	}

	/*
	 * print the specific student
	 */
	public String printAll(int i) {
		return list.get(i).toString();
	}

	/*
	 * 功能简述：将实现序列化后的对象写入到文件中。 文件输出地址："/data.txt" 文件地址可以更改
	 */
	public void fileOt() throws IOException {
		FileOutputStream fo = new FileOutputStream("/data.txt");
	
			ObjectOutputStream so = new ObjectOutputStream(fo);
			so.writeObject(list);

			System.out.println(list);

			so.close();
		

	}

	/*
	 * function: 从指定路径读取文件，然后将对象状态进行赋值使用
	 * 
	 */

	@SuppressWarnings("unchecked")
	public void fileIn() throws IOException, ClassNotFoundException {
		FileInputStream fi = new FileInputStream("/data.txt");
		
			ObjectInputStream si = new ObjectInputStream(fi);

			list = (ArrayList<Student>) si.readObject();

			si.close();
	
	}

}
